/*
 * Copyright (c) 2007, Sun Microsystems, Inc.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *  * Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in 
 *    the documentation and/or other materials provided with the distribution.
 *  * Neither the name of Sun Microsystems, Inc. nor the names of its 
 *    contributors may be used to endorse or promote products derived 
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package documenteditor;

import documenteditor.controller.CartaoFidelidadeJpaController;
import documenteditor.controller.ClienteJpaController;
import documenteditor.controller.PontoFidelidadeJpaController;
import documenteditor.controller.exceptions.NonexistentEntityException;
import documenteditor.controller.legado.ClienteLegadoJpaController;
import documenteditor.controller.legado.FinaprazoJpaController;
import documenteditor.entidade.model.CartaoFidelidade;
import documenteditor.entidade.model.ClientePessoaFisica;
import documenteditor.entidade.model.PontoFidelidade;
import documenteditor.entidade.model.Profissao;
import documenteditor.entidade.model.Telefone;
import documenteditor.entidade.model.dominio.AtivacaoPonto;
import documenteditor.entidade.model.dominio.Sexo;
import documenteditor.entidade.model.dominio.TipoValidadePonto;
import documenteditor.entidade.model.legado.ClienteLegado;
import documenteditor.entidade.model.legado.Finaprazo;
import documenteditor.view.CadastroCliente;
import documenteditor.view.CadastroPontoFidelidade;
import documenteditor.view.ConsultaClientes;
import documenteditor.view.PainelPrincipal;
import java.text.ParseException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

/**
 * This application is a simple text editor. This class displays the main frame
 * of the application and provides much of the logic. This class is called by
 * the main application class, DocumentEditorApp. For an overview of the
 * application see the comments for the DocumentEditorApp class.
 */
public class DocumentEditorView extends FrameView {

    private File file = new File("untitled.txt");
    private boolean modified = false;

    public DocumentEditorView(SingleFrameApplication app) {
        super(app);

        // generated GUI builder code
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);
        
        // connect action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    /**
     * True if the file value has been modified but not saved.  The 
     * default value of this property is false.
     * <p>
     * This is a bound read-only property.  
     * 
     * @return the value of the modified property.
     * @see #isModified
     */
    public boolean isModified() {
        return modified;
    }

    @Action
    public void cadastrarCliente() {
        CadastroCliente cd = new CadastroCliente(new ClientePessoaFisica());
        scrollPane.setViewportView(cd);
    }

    @Action
    public void importarDadosLegado() {
        progressBar.setVisible(Boolean.TRUE);
        progressBar.setIndeterminate(Boolean.TRUE);

        String dataInicio = JOptionPane.showInputDialog(mainPanel, "Digite a data inicio para importação dos clientes!", "Importação de Clientes", JOptionPane.INFORMATION_MESSAGE);

        if (dataInicio == null) {
            progressBar.setVisible(Boolean.FALSE);
            progressBar.setIndeterminate(Boolean.FALSE);
            return;
        }

        Date dtInicioCli = converteData(dataInicio);
        Date dtInicioPts = null;
        Boolean importarPts = Boolean.FALSE;

        if (dtInicioCli != null) {
            int opcao = JOptionPane.showConfirmDialog(mainPanel, "Deseja Importar Pontos?", "Realizar Importação de Pontos", JOptionPane.YES_NO_OPTION);
            if (opcao == 0) {
                importarPts = Boolean.TRUE;
                dataInicio = JOptionPane.showInputDialog(mainPanel, "Digite a data inicio para importação dos pontos!", "Importação de Pontos", JOptionPane.INFORMATION_MESSAGE);
                dtInicioPts = converteData(dataInicio);
                if (dtInicioPts == null) {
                    JOptionPane.showMessageDialog(mainPanel, "A data deve ser digitada no formato dd/mm/aaaa", "Importação de Clientes", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
        } else {
            JOptionPane.showMessageDialog(mainPanel, "A data deve ser digitada no formato dd/mm/aaaa", "Importação de Clientes", JOptionPane.ERROR_MESSAGE);
        }
        
        ClienteLegadoJpaController controllerClienteLegado = new ClienteLegadoJpaController();
        FinaprazoJpaController controllerFinaprazo = new FinaprazoJpaController();
        List<ClienteLegado> clientes = controllerClienteLegado.findClienteLegadoByDataCadastro(dtInicioCli, -1, -1, false);

        ClienteJpaController controllerCliente = new ClienteJpaController();
        ClientePessoaFisica cliente = null;
        for (ClienteLegado clienteLegado : clientes) {

            //se o cliente já existe não importa
            if (controllerCliente.findClienteByIdLegado(clienteLegado.getCodigo()) == null) {

                cliente = novoCliente(clienteLegado);

                if (importarPts) {
                    List<Finaprazo> pontos = controllerFinaprazo.findFinaprazoByCodigo(dtInicioPts, cliente.getIdLegado(), -1, -1, false);
                    for (Finaprazo finaprazo : pontos) {
                        if (finaprazo.getDevolvido().equalsIgnoreCase("NÃO")) {
                            cliente.getCartaoFidelidade().getPontoFidelidade().add(criarPonto(finaprazo, cliente.getCartaoFidelidade()));
                        }
                    }
                }
                controllerCliente.create(cliente);
            }
        }
        JOptionPane.showMessageDialog(mainPanel, "Registros importados com sucesso!", "Importação de Clientes", JOptionPane.INFORMATION_MESSAGE);
        progressBar.setVisible(false);
        progressBar.setIndeterminate(false);
    }

    private ClientePessoaFisica novoCliente(ClienteLegado clienteLegado) {
        ClientePessoaFisica cliente = new ClientePessoaFisica();
        String nome = clienteLegado.getNome();
        Sexo sexo = clienteLegado.getSexo() != null && !clienteLegado.getSexo().equals("") ? Sexo.valueOf(clienteLegado.getSexo()) : null;
        String email = clienteLegado.getEmail() == null ? clienteLegado.getEmail() : "";
        Long idLegado = clienteLegado.getCodigo();
        Date dataCadastro = clienteLegado.getCadastro();
        Date dataNascimento = clienteLegado.getDataNasc() != null ? clienteLegado.getDataNasc() : new Date();
        String cpf = clienteLegado.getCpf();
        cpf = cpf != null ? cpf.replaceAll("-", "").replaceAll(".", "") : "";
        String identidade = clienteLegado.getRg() != null ? clienteLegado.getRg() : "";

        List<Telefone> telefones = new ArrayList<Telefone>();

        Telefone telefone = criarTelefoneResidencial(clienteLegado);
        if (telefone != null) {
            telefones.add(telefone);
        }

        String profissaoStr = clienteLegado.getProfissao() != null && !clienteLegado.getProfissao().equals("") ? clienteLegado.getProfissao() : null;
        if (profissaoStr != null) {
            Profissao profissao = new Profissao();
            profissao.setNomeProfissao(profissaoStr);
            cliente.setProfissao(profissao);
        }
        
        cliente.setTelefones(telefones);
        cliente.setNomeCliente(nome);
        cliente.setSexo(sexo);
        cliente.setEmail(email);
        cliente.setIdLegado(idLegado);
        cliente.setDataCadastro(dataCadastro);
        cliente.setDataNascimento(dataNascimento);
        cliente.setCpf(cpf);
        cliente.setIdentidade(identidade);

        cliente.setCartaoFidelidade(novoCartaoFidelidade(cliente));
        return cliente;
    }

    private CartaoFidelidade novoCartaoFidelidade(ClientePessoaFisica cliente) {
        CartaoFidelidade cartao = new CartaoFidelidade();
        cartao.setDataAquisicao(new Date());
        cartao.setTipoValidadePonto(TipoValidadePonto.PERIODO_DECORRIDO);
        cartao.setAtivacaoPonto(AtivacaoPonto.ATO_DA_COMPRA);
        cartao.setCliente(cliente);
        return cartao;
    }

    @Action
    public void importarPontos() {

        progressBar.setVisible(Boolean.TRUE);
        progressBar.setIndeterminate(Boolean.TRUE);

        String dataInicio = JOptionPane.showInputDialog("Digite a data inicio para importação dos pontos!");

        if (dataInicio == null) {
            progressBar.setVisible(Boolean.FALSE);
            progressBar.setIndeterminate(Boolean.FALSE);
            return;
        }

        ClienteJpaController controllerCliente = new ClienteJpaController();
        FinaprazoJpaController controllerFinaprazo = new FinaprazoJpaController();
        CartaoFidelidadeJpaController controllerCartao = new CartaoFidelidadeJpaController();
        PontoFidelidadeJpaController controllerPontoFidelidade = new PontoFidelidadeJpaController();
        PontoFidelidade ponto = null;
        ClientePessoaFisica cliente;
        List<Long> idClientes = controllerCliente.findIdLegadoEntities();

        if (idClientes == null || idClientes.size() == 0) {
             JOptionPane.showMessageDialog(null,"Nenhum cliente cadastrado!", "Consulta de Clientes", JOptionPane.INFORMATION_MESSAGE);
             progressBar.setVisible(Boolean.FALSE);
             return;
        }


        //TODO - criar classe DataUtils
        Date dataImport = converteData(dataInicio);

        if (dataImport != null) {
            for (Long idLegado : idClientes) {
                if (idLegado == null) {
                    continue;
                }
                List<Finaprazo> pontos = controllerFinaprazo.findFinaprazoByCodigo(dataImport, idLegado, -1, -1, false);
                CartaoFidelidade cartao = controllerCartao.findCartaoFidelidadeByIdLegado(idLegado);
                //se o cliente nao tiver cartao fria um para ele
                //TODO - criar metodo para fazer isso
                if (cartao == null) {
                    cliente = (ClientePessoaFisica) controllerCliente.findClienteByIdLegado(idLegado);
                    cartao = novoCartaoFidelidade(cliente);
                    cliente.setCartaoFidelidade(cartao);
                    try {
                        controllerCliente.edit(cliente);
                    } catch (NonexistentEntityException ex) {
                        //O cartão não foi criado para o cliente - avaliar ação
                        progressBar.setVisible(Boolean.FALSE);
                        Logger.getLogger(DocumentEditorView.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        Logger.getLogger(DocumentEditorView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                for (Finaprazo finaprazo : pontos) {
                    ponto = controllerPontoFidelidade.findPontoFidelidadeByIdLegado(finaprazo.getIdFinaprazo());
                    if (ponto == null) {
                        if (finaprazo.getDevolvido().equalsIgnoreCase("NÃO")) {
                            ponto = criarPonto(finaprazo, cartao);
                            controllerPontoFidelidade.create(ponto);
                        }
                    } else {
                        ponto.setPontoValido(finaprazo.getUlt_pagamento() != null);
                    }
                }
            }
        } else {
            JOptionPane.showMessageDialog(null,"A data deve ser digitada no formato dd/mm/aaaa", "Importação de Clientes", JOptionPane.ERROR_MESSAGE);
        }
        progressBar.setVisible(Boolean.FALSE);
        progressBar.setIndeterminate(Boolean.FALSE);
    }

    private PontoFidelidade criarPonto(Finaprazo finaprazo, CartaoFidelidade cartao) {
        PontoFidelidade ponto = new PontoFidelidade();
        ponto.setIdLegado(finaprazo.getIdFinaprazo());
        ponto.setCartaoFidelidade(cartao);
        ponto.setDataAquisicao(finaprazo.getDataVenda());
        ponto.setPontoValido(finaprazo.getUlt_pagamento() != null);
        ponto.setCupom(finaprazo.getCupom());
        ponto.setQuantidade(finaprazo.getValor().intValue());
        ponto.setCupom(finaprazo.getCupom());
        return ponto;
    }

    private Date converteData(String dataStr) {
        Date data = new Date();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            data = sdf.parse(dataStr);
        } catch (ParseException ex) {
            return null;
        } catch (Exception e) {
            return null;
        }
        return data;
    }

    @Action
    public void consultarClientes() {
        ConsultaClientes cc = new ConsultaClientes();
        scrollPane.setViewportView(cc);
    }

    @Action
    public void pontuacao() {
        CadastroPontoFidelidade cdPt = new CadastroPontoFidelidade();
        scrollPane.setViewportView(cdPt);
    }

    @Action
    public void cadastrarEmpresa() {
        scrollPane.setViewportView(new PainelPrincipal());
    }

    private Telefone criarTelefoneResidencial(ClienteLegado clienteLegado) {
        Telefone telefone = null;

        String dddRes = clienteLegado.getDdd() != null ? clienteLegado.getDdd() : null;
        String telefoneRes = clienteLegado.getTelefone() != null ? clienteLegado.getTelefone() : null;
        if (dddRes != null && dddRes.length() == 3 && telefoneRes != null && telefoneRes.length() == 8) {
            telefone = new Telefone();
            telefone.setDdd(Integer.valueOf(dddRes));
            telefone.setNumeroTelefone(Long.valueOf(telefoneRes));
        }
        return telefone;
    }

    /**
     * A Task that loads the contents of a file into a String.  The
     * LoadFileTask constructor runs first, on the EDT, then the
     * #doInBackground methods runs on a background thread, and finally
     * a completion method like #succeeded or #failed runs on the EDT.
     * 
     * The resources for this class, like the message format strings are 
     * loaded from resources/LoadFileTask.properties.
     */
    private class LoadFileTask extends DocumentEditorApp.LoadTextFileTask {
        /* Construct the LoadFileTask object.  The constructor
         * will run on the EDT, so we capture a reference to the 
         * File to be loaded here.  To keep things simple, the 
         * resources for this Task are specified to be in the same 
         * ResourceMap as the DocumentEditorView class's resources.
         * They're defined in resources/DocumentEditorView.properties.
         */

        LoadFileTask(File file) {
            super(DocumentEditorView.this.getApplication(), file);
        }

       

        /* Called on the EDT if doInBackground fails because
         * an uncaught exception is thrown.  We show an error
         * dialog here.  The dialog is configured with resources
         * loaded from this Tasks's ResourceMap.
         */
        @Override
        protected void failed(Throwable e) {
            logger.log(Level.WARNING, "couldn't load " + getFile(), e);
            String msg = getResourceMap().getString("loadFailedMessage", getFile());
            String title = getResourceMap().getString("loadFailedTitle");
            int type = JOptionPane.ERROR_MESSAGE;
            JOptionPane.showMessageDialog(getFrame(), msg, title, type);
        }
    }
   

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = DocumentEditorApp.getApplication().getMainFrame();
            aboutBox = new DocumentEditorAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        DocumentEditorApp.getApplication().show(aboutBox);
    }

    /** This is a substitute for FileNameExtensionFilter, which is
     * only available on Java SE 6.
     */
    private static class TextFileFilter extends FileFilter {

        private final String description;

        TextFileFilter(String description) {
            this.description = description;
        }

        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            String fileName = f.getName();
            int i = fileName.lastIndexOf('.');
            if ((i > 0) && (i < (fileName.length() - 1))) {
                String fileExt = fileName.substring(i + 1);
                if ("txt".equalsIgnoreCase(fileExt)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public String getDescription() {
            return description;
        }
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        scrollPane = new javax.swing.JScrollPane();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem saveAsMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        javax.swing.JSeparator fileMenuSeparator = new javax.swing.JSeparator();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu editMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem cutMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem copyMenuItem = new javax.swing.JMenuItem();
        jMenuItemConsultarCliente = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem pasteMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        toolBar = new javax.swing.JToolBar();
        jToggleButtonImportarClientes = new javax.swing.JToggleButton();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        scrollPane.setName("scrollPane"); // NOI18N
        scrollPane.setViewportView(new PainelPrincipal());

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(scrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(scrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
        );
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(documenteditor.DocumentEditorApp.class).getContext().getResourceMap(DocumentEditorView.class);
        resourceMap.injectComponents(mainPanel);

        menuBar.setName("menuBar"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(documenteditor.DocumentEditorApp.class).getContext().getActionMap(DocumentEditorView.class, this);
        fileMenu.setAction(actionMap.get("importarDadosLegado")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        saveAsMenuItem.setAction(actionMap.get("importarPontos")); // NOI18N
        saveAsMenuItem.setName("saveAsMenuItem"); // NOI18N
        fileMenu.add(saveAsMenuItem);

        jMenuItem1.setAction(actionMap.get("importarDadosLegado")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        jMenuItem3.setAction(actionMap.get("pontuacao")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        fileMenu.add(jMenuItem3);

        fileMenuSeparator.setName("fileMenuSeparator"); // NOI18N
        fileMenu.add(fileMenuSeparator);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setName("editMenu"); // NOI18N

        cutMenuItem.setAction(actionMap.get("cut"));
        cutMenuItem.setName("cutMenuItem"); // NOI18N
        editMenu.add(cutMenuItem);

        copyMenuItem.setAction(actionMap.get("copy"));
        copyMenuItem.setName("copyMenuItem"); // NOI18N
        editMenu.add(copyMenuItem);

        jMenuItemConsultarCliente.setAction(actionMap.get("consultarClientes")); // NOI18N
        jMenuItemConsultarCliente.setName("jMenuItemConsultarCliente"); // NOI18N
        editMenu.add(jMenuItemConsultarCliente);

        jMenuItem2.setAction(actionMap.get("cadastrarCliente")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        editMenu.add(jMenuItem2);

        pasteMenuItem.setAction(actionMap.get("paste"));
        pasteMenuItem.setName("pasteMenuItem"); // NOI18N
        editMenu.add(pasteMenuItem);

        menuBar.add(editMenu);

        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);
        resourceMap.injectComponents(menuBar);

        toolBar.setFloatable(false);
        toolBar.setRollover(true);
        toolBar.setName("toolBar"); // NOI18N

        jToggleButtonImportarClientes.setAction(actionMap.get("importarDadosLegado")); // NOI18N
        jToggleButtonImportarClientes.setFocusable(false);
        jToggleButtonImportarClientes.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jToggleButtonImportarClientes.setName("jToggleButtonImportCli"); // NOI18N
        jToggleButtonImportarClientes.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        toolBar.add(jToggleButtonImportarClientes);
        resourceMap.injectComponents(toolBar);

        statusPanel.setName("statusPanel"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 330, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(3, 3, 3))
        );
        resourceMap.injectComponents(statusPanel);

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
        setToolBar(toolBar);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItemConsultarCliente;
    private javax.swing.JToggleButton jToggleButtonImportarClientes;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    public static javax.swing.JScrollPane scrollPane;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private static final Logger logger = Logger.getLogger(DocumentEditorView.class.getName());
}
